package dblp.crawler;

import java.util.Vector;

import dblp.merge.DBLPMerge;
import domain.Author;
import domain.Seed;
import domain.SeedStatus;

import repositories.AuthorRepository;
import repositories.PaperRepository;
import repositories.SeedRepository;

public class DBLPController {
	/*private final String[] seeds = { "Reda Alhajj", "Ken Barker",
			"Jalal Kawash", "Ehud Sharlin", "Saul Greenberg",
			"Jonathan Sillito", "Carey Williamson", "Frank Maurer" };*/

	static Object seedLock = new Object(); 
	
	private final String[] seeds = { "Jonathan Sillito" };
	
	public final int THREAD_COUNT = 8;
	public final int MAX_SEED_DEPTH = 3;
	
	private SeedRepository seedRepository;
	private ThreadGroup threadGroup;

	public DBLPController() throws Exception {
		seedRepository = new SeedRepository();
		//seedRepository.clearSeeds();
		this.addSeeds();

		threadGroup = new ThreadGroup("DBLPController");

		int threadId = 1;
		do {
			while (threadGroup.activeCount() < THREAD_COUNT) {
				Seed currentSeed = seedRepository.getCrawlSeed(MAX_SEED_DEPTH);
				if (currentSeed == null)
					break;
				
				currentSeed.setStatus(SeedStatus.Crawling);
				seedRepository.saveSeed(currentSeed);

				DBLPCrawler crawler = new DBLPCrawler(threadGroup, String.format("Crawler %-3d", threadId++), currentSeed);
				crawler.start();
				Thread.sleep(250);	// Separate out requests to prevent a heavy load initially.
			}
			
			Thread.yield();
		} while(threadGroup.activeCount() > 0);

		
		DBLPMerge merger = new DBLPMerge();
		merger.mergeAuthors();
		
		System.out.print("Finished");
	}

	private void addSeeds() {
		for (String seed : seeds) {
			seedRepository.createSeed(seed, null);
		}
	}

	public static void main(String[] args) {
		try {
			new DBLPController();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
